import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart' hide Action;

Effect<SearchViewState> buildEffect() {
  return combineEffects(<Object, Effect<SearchViewState>>{
    SearchViewAction.onClear: _onClear,
    SearchViewAction.onSearch: _onSearch,
    Lifecycle.initState: _initState,
  });
}

void _initState(Action action, Context<SearchViewState> ctx) async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  List history = prefs.getStringList(ctx.state.heroTag);
  ctx.dispatch(SearchViewActionCreator.onGetHistoryList(history ?? []));
}

void _onClear(Action action, Context<SearchViewState> ctx) async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.remove(ctx.state.heroTag);
  ctx.dispatch(SearchViewActionCreator.onGetHistoryList([]));
}

void _onSearch(Action action, Context<SearchViewState> ctx) async {
  print(action.payload);
  if (action.payload.toString().length == 0) {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    List history = prefs.getStringList(ctx.state.heroTag);
    ctx.dispatch(SearchViewActionCreator.onGetHistoryList(history ?? []));
  } else {
//    CommonUtils.showWaitLoading(ctx.context);
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String> history = prefs.getStringList(ctx.state.heroTag);
    if (history == null) {
      history = [action.payload];
    } else {
      if (history.contains(action.payload)) history.remove(action.payload);
      history.insert(0, action.payload);
    }
    prefs.setStringList(ctx.state.heroTag, history);
    ctx.dispatch(SearchViewActionCreator.onGetHistoryList(history ?? []));

    Navigator.push(
      ctx.context,
      CustomRoute(
        AppMainRoutes.routes.buildPage(RoutePath.searchResultView, {
          'type': ctx.state.type,
          'keyword': action.payload,
          'isBuildingNo': ctx.state.isAddress == 1 ? true : false,
          'tag': ctx.state.heroTag,
          'communityID': ctx.state.communityID,
          'workID': ctx.state.workID,
          'planID': ctx.state.planID,
          'status': ctx.state.status,
          'communityName': ctx.state.communityName,
        }),
      ),
    );
  }
}
